﻿Imports System.Data.OleDb
Imports System.Windows.Forms
Imports System.Drawing

Public Module Fonct_Utilitaires

    'Récupérer le Workspace (pour créer une librairie (à moins qu'une librairie de calculs temporaires existe déjà))
    'Comment récupérer le nom de la librairie de travail
    Public Sub SendData_V2(ByVal obSAS As SAS.Workspace, ByVal inputDS As DataSet)

        ' Take the provided data set and put it in a fileref in SAS as XML
        Dim obFileref As SAS.Fileref
        Dim obLibRef As SAS.Libref
        Dim assignedName As String = ""
        ' Filename websvc TEMP;

        'AssignedName est transmis en référence et contient le nom assigné
        obFileref = obSAS.FileService.AssignFileref("WebSvc", "TEMP", "", "", assignedName)
        Dim obTextStream As SAS.TextStream
        obTextStream = obFileref.OpenTextStream(
        SAS.StreamOpenMode.StreamOpenModeForWriting, 2000)
        obTextStream.Separator = " "
        obTextStream.Write("<?xml version=""1.0"" standalone=""yes"" ?>")
        obTextStream.Write(inputDS.GetXml())
        obTextStream.Close()

        ' An ADO.Net data set is capable of holding multiple tables, schemas,
        ' and relationships. This sample assumes that the ADO.Net data set
        ' only contains a single table whose name and columns fit within SAS
        ' naming rules. This would be an ideal location to use XMLMap to
        ' transform the schema of the provided data set into something that
        ' SAS may prefer.
        ' Here, the default mapping is used. Note that the LIBNAME statement
        ' uses the fileref of the same name because we did not specify a file.
        ' Using the IOM method is cleaner than using the Submit because an
        ' error is returned if there is a problem making the assignment
        obSAS.DataService.AssignLibref("WebSvc", "XML", "", "")
        ' obSAS.LanguageService.Submit("libname webSvc XML;")

        'Depuis la librairie venant d'être assignée, procéder à l'export de la table xml vers le répertoire de sortie.
        obLibRef = obSAS.DataService.AssignLibref("Dskt", "", "C:\pti\travail\omane\08_Sorties", "")
        'obSAS.LanguageService.Submit("data Dsktop.TOTO;" & vbCrLf & _
        '                             "set WebSvc;" & vbCrLf & _
        '                             "run;")
        obSAS.LanguageService.Submit("data Dskt.TOTO;" & vbCrLf & _
                                     "set WebSvc.Table1;" & vbCrLf & _
                                     "run;")

    End Sub




    'Cette méthode envoie le DataSet en paramètre au Workspace SAS indiqué et assigne le WebSvc Libref à ce dataSet
    ' This method sends the given data set to the provided workspace, and
    ' assigns the WebSvc libref to that input data set
    Private Sub SendData(ByVal obSAS As SAS.Workspace, ByVal inputDS As DataSet)

        ' Take the provided data set and put it in a fileref in SAS as XML
        Dim obFileref As SAS.Fileref
        Dim assignedName As String = "C:\Toto"

        ' Filename websvc TEMP;
        obFileref = obSAS.FileService.AssignFileref("WebSvc", "TEMP", "", "", assignedName)
        Dim obTextStream As SAS.TextStream
        obTextStream = obFileref.OpenTextStream(
        SAS.StreamOpenMode.StreamOpenModeForWriting, 2000)
        obTextStream.Separator = " "
        obTextStream.Write("<?xml version=""1.0"" standalone=""yes"" ?>")
        obTextStream.Write(inputDS.GetXml())
        obTextStream.Close()

        ' An ADO.Net data set is capable of holding multiple tables, schemas,
        ' and relationships. This sample assumes that the ADO.Net data set
        ' only contains a single table whose name and columns fit within SAS
        ' naming rules. This would be an ideal location to use XMLMap to
        ' transform the schema of the provided data set into something that
        ' SAS may prefer.
        ' Here, the default mapping is used. Note that the LIBNAME statement
        ' uses the fileref of the same name because we did not specify a file.
        ' Using the IOM method is cleaner than using the Submit because an
        ' error is returned if there is a problem making the assignment
        obSAS.DataService.AssignLibref("WebSvc", "XML", "", "")
        ' obSAS.LanguageService.Submit("libname webSvc XML;")
    End Sub

#Region "Manipulation des listView"

    'OperationCollection = REPLACE => La nouvelle collection de correspondance remplace entièrement l'ancienne
    'OperationCollection = ADD => Une correspondance est ajoutée à la liste des correspondances de la listView
    Public Function ltvFunc_modifCollCorresp(ByVal ltvAMAJ As ListView, _
                                           ByVal lCorrespondances As Dictionary(Of String, Correspondance), _
                                           ByVal operation As PTIC_GestionBDD.operationCollection) As Boolean

        ltvAMAJ.BeginUpdate()

        'Ajout des groupes s'ils ne sont pas présents dans la listView
        If ltvAMAJ.Groups().Count = 0 Or operation = operationCollection.REPLACE Then
            ltvAMAJ.Clear()
            ltvAMAJ.Columns.Add("Nom variable", 200)
            Dim groupVarChar As New ListViewGroup("gpeVarChar", "Variables chaîne de caractère")
            groupVarChar.HeaderAlignment = HorizontalAlignment.Left
            ltvAMAJ.Groups.Add(groupVarChar)
            Dim groupVarNum As New ListViewGroup("gpeVarNum", "Variables numériques")
            groupVarNum.HeaderAlignment = HorizontalAlignment.Left
            ltvAMAJ.Groups.Add(groupVarNum)
            Dim groupVarDate As New ListViewGroup("gpeVarDate", "Variables date")
            groupVarDate.HeaderAlignment = HorizontalAlignment.Left
            ltvAMAJ.Groups.Add(groupVarDate)
        End If

        If operation = operationCollection.ADD Or operation = operationCollection.REPLACE Then
            For Each corresp As Correspondance In lCorrespondances.Values
                Dim it As New ListViewItem(corresp.description)
                it.Font = New Font("Tahoma", 9, FontStyle.Regular)
                it.Name = corresp.description
                Select Case corresp.chOutil.Format.typeStock.Name
                    Case "Double"
                        it.ImageKey = "varNum16"
                        ltvAMAJ.Groups("gpeVarNum").Items.Add(it)
                    Case "String"
                        ltvAMAJ.Groups("gpeVarChar").Items.Add(it)
                        it.ImageKey = "varCar16"
                    Case "DateTime"
                        ltvAMAJ.Groups("gpeVarDate").Items.Add(it)
                        it.ImageKey = "varDate16"
                End Select
                ltvAMAJ.Items.Add(it)
            Next
        ElseIf operation = operationCollection.REMOVE Then
            For Each ltv_it As ListViewItem In ltvAMAJ.Items
                If lCorrespondances.ContainsKey(ltv_it.Text) Then
                    ltv_it.Remove()
                End If
            Next
        End If
        ltvAMAJ.EndUpdate()
        Return True
    End Function

#End Region

#Region "Mise à jour des formats des dataGridView"
    Public Sub MAJdgvFormats(ByVal lstCorresp As IDictionary(Of String, Correspondance), _
                             ByVal dgv As DataGridView)
        For Each corresp As Correspondance In lstCorresp.Values
            If dgv.Columns.Contains(corresp.chOutil.Nom) Then
                If corresp.chOutil.Format.formatAff <> "" Then _
                    dgv.Columns(corresp.chOutil.Nom).DefaultCellStyle.Format = corresp.chOutil.Format.formatAff
                dgv.Columns(corresp.chOutil.Nom).HeaderText = corresp.description
            End If
        Next
        'If dgv.Columns.Contains() Then
    End Sub
#End Region

    Public Function getCodeHexaColor(ByVal c As Color) As String
        Return String.Format("#{0:X2}{1:X2}{2:X2}", c.R, c.G, c.B)
    End Function

    Public Sub soumettreCodeSAS()
        Dim nomFichierConnection As New Cla_NomFichier("C:\Pti\Travail\3005 - NATIXIS ASSURANCES\01_OMANE\01_BasesEncours\_04_base_bplc_retraitee_v2.sas7bdat")
        'Création de la connection faisant référence à l'espace de travail
        'de l'objet
        'Dim obWM As New SASWorkspaceManager.WorkspaceManager
        Dim obSAS As New SAS.Workspace
        Dim obLibRef As SAS.Libref
        Dim conn As New OleDbConnection
        'Etablissement d'un espace de travail SAS 
        'obSAS = obWM.Workspaces.CreateWorkspaceByLogicalName _
        '        ("Session_Travail", SASWorkspaceManager.Visibility.VisibilityProcess, "", "", "")
        'Assignation d'une référence à cet espace de travail
        obLibRef = obSAS.DataService.AssignLibref("mylib", "", nomFichierConnection.NomRepertoire, "")
        'Open a connection.
        conn.ConnectionString = "Provider=sas.IOMProvider.1;SAS Workspace ID=" & obSAS.UniqueIdentifier
        obSAS.LanguageService.Submit("data mylib.TOTO;" & vbCrLf & _
                                     "set myLib._04_base_bplc_retraitee_v2;" & vbCrLf & _
                                     "COMPTEUR=_N_;" & vbCrLf & _
                                     "run;")

        'SASObjectManager.
    End Sub

    'Initialisation d'une connection oleDB ACCESS
    Public Function ACCESS_initOleDbConnection(ByVal nomFichierConnection As Cla_NomFichier)
        Dim conn As New OleDbConnection
        conn.ConnectionString = "provider=Microsoft.jet.oledb.4.0;" & _
                              "data Source= " & nomFichierConnection.NomComplet & ";"
        Return conn
    End Function

#Region "Manipulation des codes couleur"
    Public Function RVBtoVBhexa(ByVal rouge As Byte, ByVal vert As Byte, ByVal bleu As Byte) As String
        Dim result As String = "&H"
        result = IIf(Len(Hex(bleu)) = 1, result & "0" & Hex(bleu), result & Hex(bleu))
        result = IIf(Len(Hex(vert)) = 1, result & "0" & Hex(vert), result & Hex(vert))
        result = IIf(Len(Hex(rouge)) = 1, result & "0" & Hex(rouge), result & Hex(rouge))
        Return result
    End Function
    Public Function hexaToDecimal(ByVal valeurHexa As String) As Integer
        Throw New NotImplementedException()
    End Function
#End Region

End Module

Public Module loki
    Sub Main()
        Dim obs As New ObservableDictionaryV3(Of String, DateTime)
        Dim testobj As New test(Of String, DateTime)(obs)
        obs.Add("hahaha", Now)
        Dim d As DateTime = obs("hahaha")
        MsgBox(obs.ContainsKey("hahaha"))
        obs.Item("hahaha") = New DateTime(10000)

        obs.Remove("hahaha")
    End Sub

    Class test(Of a, b)

        Private WithEvents obs As ObservableDictionaryV3(Of a, b)
        Sub New(ByVal obs As ObservableDictionaryV3(Of a, b))
            Me.obs = obs
        End Sub

        'Private Sub obs_CollectionChanged(ByVal sender As Object, ByVal e As System.Collections.Specialized.NotifyCollectionChangedEventArgs) Handles obs.DictionaryChanged
        '    MsgBox(e.Action.ToString())
        'End Sub

        'Private Sub obs_PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Handles obs.PropertyChanged

        'End Sub
    End Class

End Module